package com.aos.eap.activity;

import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.aos.eap.R;
import com.aos.eap.adapter.MagazineListAdapter;
import com.aos.eap.base.BaseDialogActivity;
import com.aos.eap.base.Constant;
import com.aos.eap.bean.MagazineBean;
import com.aos.eap.bean.WorkExceptionEndBean;
import com.aos.eap.bean.net.BaseResponseBean;
import com.aos.eap.utils.MyUtils;
import com.aos.eap.utils.NetUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static com.aos.eap.utils.AnimationUtils.arrowAnimation;

public class MFG_WorkExceptionEndActivity extends BaseDialogActivity {


    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.ivInfoArrow)
    ImageView ivInfoArrow;
    @BindView(R.id.llInfoTitle)
    LinearLayout llInfoTitle;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.tvReason)
    TextView tvReason;
    @BindView(R.id.ivReasonArrow)
    ImageView ivReasonArrow;
    @BindView(R.id.flReason)
    FrameLayout flReason;
    @BindView(R.id.tvLotId)
    TextView tvLotId;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.rbYes)
    RadioButton rbYes;
    @BindView(R.id.rbNo)
    RadioButton rbNo;
    @BindView(R.id.llInfo)
    LinearLayout llInfo;
    @BindView(R.id.ivMagazineArrow)
    ImageView ivMagazineArrow;
    @BindView(R.id.llMagazineTitle)
    LinearLayout llMagazineTitle;
    @BindView(R.id.etMagazineId)
    FreeUI_ClearEditText etMagazineId;
    @BindView(R.id.tvRemove)
    TextView tvRemove;
    @BindView(R.id.cbCheckAll)
    CheckBox cbCheckAll;
    @BindView(R.id.rvMagazineList)
    RecyclerView rvMagazineList;
    @BindView(R.id.llMagazine)
    LinearLayout llMagazine;
    @BindView(R.id.ivMessageArrow)
    ImageView ivMessageArrow;
    @BindView(R.id.llMessageTitle)
    LinearLayout llMessageTitle;
    @BindView(R.id.rvMessageList)
    RecyclerView rvMessageList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private MagazineListAdapter magazineListAdapter;
    private WorkExceptionEndBean workExceptionEndBean;
    private FreeUI_GeneralPop codePop;

    @OnClick({R.id.flReason, R.id.tvRemove, R.id.llInfoTitle, R.id.llMagazineTitle, R.id.llMessageTitle})
    public void onViewClicked(View view) {
        if (MyUtils.isFastClick()){
            showToast("您点击的太快了",false);
            return;
        }
        switch (view.getId()) {
            case R.id.flReason:
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivReasonArrow);
                        codePop.showAsDropDown(flReason, 0, 0);
                    }
                }
                break;
            case R.id.tvRemove:
                List<MagazineBean> removeList = new ArrayList<>();
                for (MagazineBean magazineBean : magazineListAdapter.getData()) {
                    if (magazineBean.isSelect()) {
                        removeList.add(magazineBean);
                    }
                }
                if (removeList.size() > 0) {
                    magazineListAdapter.clearPos();
                    magazineListAdapter.getData().removeAll(removeList);
                    magazineListAdapter.notifyDataSetChanged();
                    cbCheckAll.setChecked(false);
                } else {
                    showToast("未勾选，不能移除", false);
                }
                break;
            case R.id.llInfoTitle:
                if (llInfo.getVisibility() == View.VISIBLE) {
                    llInfo.setVisibility(View.GONE);
                    arrowAnimation(ivInfoArrow, 1);
                } else {
                    llInfo.setVisibility(View.VISIBLE);
                    arrowAnimation(ivInfoArrow, 2);
                }
                break;
            case R.id.llMagazineTitle:
                if (llMagazine.getVisibility() == View.VISIBLE) {
                    llMagazine.setVisibility(View.GONE);
                    arrowAnimation(ivMagazineArrow, 1);
                } else {
                    llMagazine.setVisibility(View.VISIBLE);
                    arrowAnimation(ivMagazineArrow, 2);
                }
                break;
            case R.id.llMessageTitle:
                if (rvMessageList.getVisibility() == View.VISIBLE) {
                    rvMessageList.setVisibility(View.GONE);
                    arrowAnimation(ivMessageArrow, 1);
                } else {
                    rvMessageList.setVisibility(View.VISIBLE);
                    arrowAnimation(ivMessageArrow, 2);
                }
                break;
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_exception_end;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        rvMagazineList.setLayoutManager(new LinearLayoutManager(MFG_WorkExceptionEndActivity.this));
        rvMagazineList.setItemAnimator(new DefaultItemAnimator());
        rvMagazineList.addItemDecoration(new DividerItemDecoration(MFG_WorkExceptionEndActivity.this, 1));
        MyUtils.setEditTextListener(etEqpId, this, this::requestInfoByEqpId);
        MyUtils.setEditTextListener(etMagazineId, this, s -> {
            boolean isHave = false;
            for (MagazineBean entity : magazineListAdapter.getData()) {
                if (entity.getMagazineID().equalsIgnoreCase(s)) {
                    isHave = true;
                    break;
                }
            }
            if (isHave) {
                MyUtils.setEditTextFocus(etMagazineId);
                etMagazineId.setText("");
                showToast("编号已存在列表中", false);
            } else {
                MagazineBean magazineBean = new MagazineBean();
                magazineBean.setMagazineID(s);
                magazineListAdapter.addData(0, magazineBean);
//                rvMagazineList.smoothScrollToPosition(0);
                MyUtils.setEditTextFocus(etMagazineId);
                etMagazineId.setText("");
            }
        });
    }

    private void requestInfoByEqpId(String eqpId) {
        JsonObject map = new JsonObject();
        map.addProperty("EqpID", eqpId);
        NetUtils.requestGetNet(this, "EMS_TrackOutExceptLoad", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<WorkExceptionEndBean>>(
                new TypeToken<BaseResponseBean<WorkExceptionEndBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<WorkExceptionEndBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true,getSupportFragmentManager())) {
                    workExceptionEndBean = response.body().getResponse().getBody();
                    setPageData(workExceptionEndBean);
                }else {
                    workExceptionEndBean = null;
                    setPageData(new WorkExceptionEndBean());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<WorkExceptionEndBean>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_TrackOutExceptLoad");
                workExceptionEndBean = null;
                setPageData(new WorkExceptionEndBean());
            }
        });
    }
    private void setPageData(WorkExceptionEndBean workExceptionEndBean) {
        tvLotId.setText(workExceptionEndBean.getLotID());
        magazineListAdapter.setNewData(workExceptionEndBean.getMagazineList());
        codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(),
                flReason.getWidth(),workExceptionEndBean.getExceptionList(), ivReasonArrow, (s, i) -> {
                    tvReason.setText(s);
                });
    }
    @Override
    protected void initData() {
        cbCheckAll.setOnCheckedChangeListener((compoundButton, isChecked) -> magazineListAdapter.setAll(isChecked));
        magazineListAdapter = new MagazineListAdapter(null);
        magazineListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        magazineListAdapter.isFirstOnly(true);
        rvMagazineList.setAdapter(magazineListAdapter);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("异常结束");
        freeUI_titleView.setLeftListener(view -> showBackDialog(MFG_WorkExceptionEndActivity.this));
        freeUI_titleView.setRightListener("提交", v -> {
            if (MyUtils.isFastClick()){
                showToast("您点击的太快了",false);
                return;
            }
            if (workExceptionEndBean == null) {
                showToast("未获取到页面信息，请重新扫描设备编号", false);
                MyUtils.setEditTextFocus(etEqpId);
                etEqpId.setText("");
                return;
            }
            String reason = tvReason.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(reason)) {
                showToast("请选择异常原因", false);
                return;
            }
            if (magazineListAdapter.getData().size() == 0) {
                showToast("Magazine列表不能为空", false);
                return;
            }
            JsonObject map = new JsonObject();
            map.addProperty("EqpID", workExceptionEndBean.getEqpID());
            map.addProperty("LotID", workExceptionEndBean.getLotID());
            map.addProperty("FaultDesc", reason);
            map.add("MagazineList", new JsonParser().parse(new Gson().toJson(magazineListAdapter.getData())).getAsJsonArray());
            map.addProperty("Remark", etRemark.getText().toString().trim());
            requestExceptionOut(map);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    private void requestExceptionOut(JsonObject map) {
        NetUtils.requestGetNet(this, "EMS_TrackOutExcept", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(getApplicationContext(), false,getSupportFragmentManager())) {
                    showToast("提交成功", true);
                    new Handler().postDelayed(MFG_WorkExceptionEndActivity.this::finish, 2000);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_TrackOutExcept");
            }
        });
    }
}
